import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;

import lejos.nxt.LCD;
import lejos.nxt.Sound;
import lejos.nxt.comm.Bluetooth;
import lejos.nxt.comm.NXTCommConnector;
import lejos.nxt.comm.NXTConnection;


public class NXTBluetooth extends Thread{
 	ThreadCommunication comm;
	 public static NXTConnection BTLink;
	 public static DataInputStream inputStream; 
	 public static DataOutputStream outputStream;
	 public NXTBluetooth(){
	}

	 public NXTBluetooth (ThreadCommunication comm) {
		 this.comm = comm;
	 }
	 
	public void run(){
		
		try {
			connectBluetooth();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
    
	public void connectBluetooth() throws IOException
	{
		

        NXTCommConnector[] connectors = {Bluetooth.getConnector()};
        int[] modes = {NXTConnection.PACKET, NXTConnection.RAW};

        while (true)
        {
            LCD.clear();
            LCD.drawString("Connecting...", 0, 0);

            NXTConnection con = connectors[0].waitForConnection(0, modes[0]);

            LCD.clear();
            LCD.drawString("Connected...", 0, 0);
            Sound.beepSequence();

            DataInputStream dis = con.openDataInputStream();
            DataOutputStream dos = con.openDataOutputStream();

            ResponseMessage reply;
            
            while(true)
            {
                String n;
                try{
                    n = dis.readUTF();
                    ReceivedMessage recMsg = new ReceivedMessage(n);
                    comm.addReceivedMessage(recMsg);
                } catch (EOFException e)
                {
                	System.out.println("EOFexception: " + e);
                    break;
                }
                LCD.drawString("Read: ", 0, 4);
                LCD.drawString(n, 7, 6);
                
                reply = comm.getResponseMessage();
                while( reply == null)
                	reply = comm.getResponseMessage();
                dos.writeUTF(reply.getXML());
                dos.flush();
            }

            LCD.drawString("Closing...  ", 0, 2);
            dis.close();
            dos.close();
            con.close();
        }
		
        }

	
	

}
